#include <memory>
#include <iostream>
#include <vector>

using std::cout;
using std::endl;
using std::vector;
using std::shared_ptr;

class Point
{
public:
    Point(int ix, int iy)
    : _ix(ix)
    , _iy(iy)
    {   cout << "Point(int,int)" << endl;   }

    ~Point()
    {   cout << "~Point()" << endl; }

    void print() const
    {   
        cout << "(" << _ix
             << "," << _iy
             << ")" << endl;
    }

private:
    int _ix;
    int _iy;
};

shared_ptr<Point> getValue()
{
    shared_ptr<Point> pPoint(new Point(10, 11));
    return pPoint;//调用shared_ptr的移动构造函数
}

void test0()
{
    //pt是原生的裸指针，没有进行托管的地址值
    Point * pt = new Point(1, 2);
    cout << "pt:" << pt << endl;
    shared_ptr<Point> sp(pt);
    sp->print();
    (*sp).print();
    cout << "sp.get():" << sp.get() << endl;
    cout << "sp' use_count:" << sp.use_count() << endl;
    cout << endl;

    //拷贝构造函数
    shared_ptr<Point> sp2 = sp;//ok
    sp2->print();
    (*sp2).print();
    cout << "sp' use_count:" << sp.use_count() << endl;
    cout << "sp2' use_count:" << sp2.use_count() << endl;
    cout << "sp2.get():" << sp2.get() << endl;
    cout << endl;

#if 1
    vector<shared_ptr<Point>> vec;
    //sp不能直接放到容器中，默认情况下会直接进行复制
    vec.push_back(sp);//执行拷贝
    //shared_ptr具有移动语义，可以转移到容器中
    vec.push_back(std::move(sp));
    cout << "vec'size:" << vec.size() << endl;
    cout << "通过数组元素来访问:";
    vec[0]->print();

    //当sp被转移走了之后，内部的指针就被置为空指针了
    //sp->print();//这里会报段错误

    cout << endl;
    //&getValue();//右值
    shared_ptr<Point> sp3 = getValue();//调用移动构造函数
    sp3->print();
#endif

}


int main()
{
    test0();

    return 0;
}

